//index.js
//获取应用实例
const app = getApp()

var apiHost = wx.getStorageSync('apiHost');
var yunId = wx.getStorageSync('yunId');
// var openId = wx.getStorageSync('openId');
// var userInfo = wx.getStorageSync('userInfo');

//不带177的正则表达式
// var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;  
var myreg = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/;  

// 60秒倒计时
var countdown = 60;
var settime = function (that) {
  if (countdown == 0) {
    that.setData({
      is_show: true
    })
    countdown = 60;
    return;
  } else {
    that.setData({
      is_show: false,     //判断倒计时
      last_time: countdown
    })
    countdown--;
  }
  setTimeout(function () {
    settime(that)
  }, 1000)
}

Page({
  data: {
    userNameVlue : '',    //手机号
    codeVlue : '',
    last_time: '',        //倒计时
    is_show: true,        //是否展示
    is_phone: false,      //是否提示
    is_code: false,
    hiddenLoading: true,  //加载动画
    is_disabled: false,
    ts_msg:'',
    openId : ''
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  //页面初始化加载
  onLoad: function (options) {
    var that = this;

    if (options.openId != undefined) {
      that.setData({
        openId: options.openId
      });
    }
  },

  //按钮获取用户信息
  loginHd:function(res){
    var that = this;

    var errMsgFlg = res.detail.errMsg

    if ("getUserInfo:ok" == errMsgFlg){
      var userCon = res.detail
      wx.login({
        success: function (r) {
          var code = r.code;//登录凭证
          if (code) {
            that.VERBurl(userCon, code) 
            wx.showToast({
              title: '登录成功',
              icon: 'none',
              duration: 2000,
              mask: true
            });
          } else {
            
            wx.showToast({
              title: '获取用户登录态失败！' + r.errMsg,
              icon: 'none',
              duration: 2000,
              mask: true
            });
          }
        },
        fail: function () {
          
          wx.showToast({
            title: '登陆失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      })
    }
  },

   /**
   * 解密用户登录完成后的url
   */
  VERBurl: function (res, code){
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息  (注意：这个东西必须需要 开放平台 授权)
    wx.request({
      url: apiHost + 'xcx/UserInfo/decodeUserInfo',//自己的服务接口地址
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: { 
        encryptedData: res.encryptedData, 
        iv: res.iv, 
        code: code,
        Appid:'wx910d63f3cec2d59b',
        Secret:'3f8216c7ada3554a4701e67e729b839b'
      },
      success: function (data) {
        //4.解密成功后 获取自己服务器返回的结果
        if (data.data.status == 1) {
          var userInfo_ = data.data.userInfo;
          var openIdFl = userInfo_.openId;

          wx.setStorageSync('userId', userInfo_.unionId);
          wx.setStorageSync('openId', openIdFl);
          wx.setStorageSync('session_token', userInfo_.session_key);
          wx.setStorageSync('userInfo', userInfo_);

          that.setData({
            openId: openIdFl,
            userInfo: userInfo_
          });

          that.platformLogin(openIdFl)  //平台登录
        } else {
          
          wx.showToast({
            title: '解密失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {
        
        wx.showToast({
          title: '系统错误',
          icon: 'none',
          duration: 2000,
          mask: true
        });
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 平台登录
   */
  platformLogin: function (openIdFl) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + 'xcx/login/in',//自己的服务接口地址
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        openId: openIdFl,
        yunId: yunId
      },
      success: function (data) {
        var code = data.data.code;     //调用是否成功标识
        var dataFlag = data.data.data; //判断是云店主的标识
        wx.hideLoading();   //隐藏加载loading

        //如果调用成功 判断跳转
        if (code == "10000") {
          // 跳转云店主主页
          if (dataFlag == "storeBoss") {
            wx.navigateTo({
              url: '../yunShopIndex/yunShopIndex',
              success: function () {
                wx.hideLoading();   //隐藏加载loading
              },
            });
          } else
            // 跳转普通用户主页
            if (dataFlag == "userCommon") {
              wx.switchTab({
                url: '../Zindex/Zindex',
                success: function () {
                  wx.hideLoading();   //隐藏加载loading
                },
              });
            }
        } else {
          that.getCode(); //如果在平台里面没有申请，就发送验证码
        }
      },
      fail: function () {
        
        wx.showToast({
          title: '系统错误',
          icon: 'none',
          duration: 2000,
          mask: true
        });
        
      }
    })
  },

  //获取手机输入框内容
  userNameInput: function(e) {
    var that = this ; 
    that.setData({
      userNameVlue: e.detail.value
    })
    var code = that.data.codeVlue;      //验证码
    var userNameVlue = e.detail.value;  //手机号

    if (code.length == 6 && userNameVlue.length == 11) {
      that.setData({
        is_disabled: true
      });
    } else {
      that.setData({
        is_disabled: false
      });
    }
  },
  //获取手机输入框内容
  codeInput : function(e){
    var that = this;
    var code = e.detail.value;                  //验证码
    var userNameVlue = that.data.userNameVlue;  //手机号
    console.log(userNameVlue)
    if (code.length == 6 && userNameVlue.length==11){
      that.setData({
        is_disabled: true
      });
    }else{
      that.setData({
        is_disabled: false
      });
    }
    that.setData({
      codeVlue: code,
    });
  },

  // 点击获取验证码
  getCode : function(){
    var that = this;

    var userName = that.data.userNameVlue;

    if (!myreg.test(userName)) {
      that.setData({
        is_phone: true     //提示信息
      })
      return;
    }else{
      that.setData({
        is_phone: false   //提示信息
      }) 
    }
    var that = this;
    // 将获取验证码按钮隐藏60s，60s后再次显示
    that.setData({
      is_show: (!that.data.is_show)  //false
    })
    settime(that);  //倒计时

    that.sendCode(userName)//发送验证码

  },
  /**
   * 发送验证码
   */
  sendCode: function (userName){
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    //获取店铺详情
    wx.request({
      url: apiHost + "mobile/login/code",
      data: {
        phone: userName  //测试云店主id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {
        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '系统错误',
          icon: 'none',
          duration: 2000,
          mask: true
        });

      }
    });
  },
  //表单提交
  formSubmit: function (e) {
    var that = this;
    var formData = e.detail.value;        //表单提交的整体jso
    var openId = that.data.openId;
    var userInfo = that.data.userInfo;

    var userPhone = formData.userPhone;   //手机号码
    var code = formData.code;             //手机验证码
    var nickName = userInfo.nickName;     //	昵称
    var avatarUrl = userInfo.avatarUrl;   //用户头像
    var gender = userInfo.gender;         //性别1为男，0为女
    var city = userInfo.city;             //城市
    var country = userInfo.country;       //国家
    var province = userInfo.province;     //省

    wx.request({
      url: apiHost + "xcx/login/reg",
      data: {
        // openId: 'olGet4mNKn1FeKEvSrGiMuY6v3ZB',
        openId : openId,
        yunId : yunId,
        userPhone:  userPhone,
        nickName:  nickName,
        code:  code,
        avatarUrl:  avatarUrl,
        gender:  gender,
        city:  city,
        country:  country,
        province:  province
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {

        if(res.data.code=='10004'){
          that.setData({
            is_code: true,        //提示信息
            ts_msg: res.data.msg
          })
        }
        if(res.data.code=='10000'){
          that.setData({
            is_code: true,        //提示信息
            ts_msg: '　'
          })
           //跳转普通用户主页
            wx.showToast({
              title: '加载中',
              icon: 'loading',
              mask: true
            })
            wx.switchTab({
              url: '../Zindex/Zindex'
            });
        }else{
          that.setData({
            is_code: (!that.data.is_phone),   //提示信息
            ts_msg: res.data.msg
          }) 
        }
      },
    });

  },
})
